<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Cache;

class ArtisanCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'll {chunk_size? : 展示列数（默认：6）}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '以一个新的方式展示 Artisan 命令。';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $cache_chunk_size = Cache::get('artisan_list_chunk_size', 6);
        $chunk_size = is_null($this->argument('chunk_size')) ? $cache_chunk_size : $this->argument('chunk_size');
        Cache::put('artisan_list_chunk_size', $chunk_size);
        $artisan_lists = Artisan::all();
        $list = [];
        foreach ($artisan_lists as $key => $item) {
            $list[] = $key;
        }
        $list = Arr::sort($list);
        $list = array_values($list);
        $chunks = collect($list)->chunk($chunk_size)->toArray();
        foreach ($chunks as &$chunk) {
            foreach ($chunk as $key => &$artisan_name) {
                $artisan_name = "{$key}.{$artisan_name}";
            }
            unset($artisan_name);
        }
        unset($chunk);
        $headers = [];
        for ($i = 0; $i < $chunk_size; $i++) {
            $headers[] = 'Command';
        }
        $this->table(
            $headers,
            $chunks,
            'box'
        );
        $artisan = $this->anticipate('想要执行的 Artisan 命令（也可以输入编号）（可携带参数，如：route:list --path=login; 163 --path=login）', $list);
        if (is_numeric($artisan) && !empty($list[$artisan])) {
            $artisan = $list[$artisan];
        }
        if (Str::contains($artisan, ' ')) {
            $artisan_arr = explode(" ", $artisan);
            if (is_numeric($artisan_arr[0]) && !empty($list[$artisan_arr[0]])) {
                $artisan_arr[0] = $list[$artisan_arr[0]];
                $artisan = implode(" ", $artisan_arr);
            }
        }

        $this->info("执行 php artisan {$artisan} 命令：");
        passthru("php artisan {$artisan}");
        return;
    }
}
